const bcrypt = require('bcryptjs');
const {Model, DataTypes} = require('sequelize');
const sequelize = require('../../core/db');

class Admin extends Model {

  /**
   * 获取管理员账号对应的所有角色所拥有的所有权限
   * @param admin_id
   * @return {Promise<*[]>}
   */
  static async getPerms(admin_id) {
    const res = await this.findOne({
      include: [{all: true, nested: true}]
      , where: {
        id: admin_id
      }
    });

    //该用户所拥有的所有角色所拥有的权限列表
    const perms = [];
    if (res.Roles.length !== 0) {
      res.Roles.forEach(role => {
        if (role.Menus.length !== 0) {
          perms.push(...role.Menus.map(menu => menu.perms).filter(menu => menu));
        }
      });
    }

    // 多个角色之间可能存在相同的权限,这里进行去重
    return Array.from(new Set(perms));
  }
}

Admin.init({
  id: {
    type: DataTypes.INTEGER.UNSIGNED
    , primaryKey: true
    , autoIncrement: true
  }
  , username: {
    type: DataTypes.STRING
    , allowNull: false
    , unique: true
  }
  , password: {
    type: DataTypes.STRING
    , allowNull: false
    , set(val) {
      const salt = bcrypt.genSaltSync(10/*花费的时间成本,数值越大安全性越高*/);
      const psw = bcrypt.hashSync(val, salt);
      /*this指代的是User实例*/
      this.setDataValue('password', psw);
    }
  }
  , status: {
    type: DataTypes.BOOLEAN
    , allowNull: false
    , defaultValue: true
    , comment: '状态 0:禁用 1：启用'
  }
  , phone: {
    type: DataTypes.STRING
    , unique: true
  }
  , email: {
    type: DataTypes.STRING
    , unique: true
  }
  , nickname: {
    type: DataTypes.STRING
    , unique: true
  }
  , remark: {
    type: DataTypes.STRING
  }
}, {
  sequelize
  , tableName: 'admin'
});

module.exports = Admin;
